<?php

namespace app\adminapi\middleware;

use app\common\cache\AdminTokenCache;
use app\common\service\JsonService;
use think\facade\Db;
use think\facade\Request;
use think\facade\Config;
use app\adminapi\service\AdminTokenService;

/**
 * 后台权限中间件
 */
class Auth
{
    public function handle($request, \Closure $next)
    {
        $pathInfo = $request->pathinfo();

        if ($pathInfo == 'user/login') {
            return $next($request);
        }

        $token = Request::header("token");

        if (empty($token)) {
            return JsonService::fail('请求参数缺少token', 1, 420);
        }

        $tokenInfo = (new AdminTokenCache())->getAdminInfo($token);

        if (empty($tokenInfo)) {
            return JsonService::fail('登录超时，请重新登录', 1, 420);
        }

        $userId = $tokenInfo["admin_id"];

        $user = Db::name("admin")->where("id", $userId)->find();

        if ($user['root'] == 1) {
            $accountRule = Db::name("admin_rule")->where("type", 2)->column("api_url");
        } else {
            $groupId = Db::name("admin")->where("id", $userId)->value("group_id");
            $ruleIds = Db::name("admin_group_rule")->where("group_id", $groupId)->column("rule_id");
            $accountRule = Db::name("admin_rule")->where("type", 2)->where("id", "in", $ruleIds)->column("api_url");

            if (!in_array($pathInfo, $accountRule)) {
                return JsonService::fail('权限不足，无法访问或操作' );
            };
        }

        //获取临近过期自动续期时长
        $beExpireDuration = Config::get('project.admin_token.be_expire_duration');
        //token续期
        if (time() > ($tokenInfo['expire_time'] - $beExpireDuration)) {
            $result = AdminTokenService::overtimeToken($token);
            //续期失败（数据表被删除导致）
            if (empty($result)) {
                return JsonService::fail('登录过期', 1, 420);
            }
        }

        $request->adminInfo = $user;

        return $next($request);
    }
}
